package com.begamer.card.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.begamer.card.cache.Cache;
import com.begamer.card.common.util.RequestUtil;
import com.begamer.card.common.util.StringUtil;
import com.begamer.card.json.command2.AnnounceResultJson;
import com.begamer.card.log.ErrorLogger;
import com.begamer.card.model.pojo.Announce;

public class AnnounceController extends AbstractMultiActionController{

	private static final Logger errorlogger = ErrorLogger.logger;
	
	public ModelAndView showAnnounce(HttpServletRequest request,HttpServletResponse response)
	{
		try
		{
			long time = System.currentTimeMillis();
			AnnounceResultJson aj = new AnnounceResultJson();
			List<Announce> announces = Cache.instance.getAnnounces();
			List<Announce> list = new ArrayList<Announce>();
			if (announces!=null && announces.size()>0)
			{
				for (int i = 0; i < announces.size(); i++)
				{
					Announce e = announces.get(i);
					int subTime = StringUtil.getSubSecond(e.getTime(), time);
					int lastSubAddTime = StringUtil.getSubSecond(e.getCurTime(), time);
					if (lastSubAddTime>=(e.getFrequency()*60) && subTime<=(e.getFrequency()*e.getNum()*60) && e.getNum()>1)
					{
						e.setCurTime(time);
						list.add(e);
					}
					if (e.getNum() == 1)
					{
						list.add(e);
					}
				}
			}
			//生成即时公告
			//12点，18点生成回复体力公告
			String date1 = "12:00:00";
			String date2 = "12:01:00";
			String date3 = "18:00:00";
			String date4 = "18:01:00";
			String today =StringUtil.getDate(time);
			long t1 =StringUtil.getTimeStamp(today+" "+date1);
			long t2 =StringUtil.getTimeStamp(today+" "+date2);
			long t3 =StringUtil.getTimeStamp(today+" "+date3);
			long t4 =StringUtil.getTimeStamp(today+" "+date4);
			if(time-t1>=0 && time-t2<=0)//12
			{
				Announce e = Announce.createAnnounce(0,"亲爱的玩家，我们为您准备了丰盛的午餐，请来享用吧！", 1, 1, 1);
				list.add(e);
			}
			if ((time-t3>=0 && time-t4<=0))//18
			{
				Announce e = Announce.createAnnounce(0,"亲爱的玩家，我们为您准备了丰盛的晚餐，请来享用吧！", 1, 1, 1);
				list.add(e);
			}
			aj.announces=list;
			Cache.recordRequestNum(aj);
			String msg = JSON.toJSONString(aj);
			logger.info("msg:"+msg);
			RequestUtil.setResponseMsg2(request, msg);
			return new ModelAndView("/user/result.vm");
		}
		catch (Exception e)
		{
			errorlogger.error(this.getClass().getName() + "->"+ Thread.currentThread().getStackTrace()[1].getMethodName()+ "():", e);
		}
		return new ModelAndView("/user/result.vm");
	}
}